package com.zhku.shoppingspringboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.corba.se.spi.ior.ObjectKey;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.zhku.shoppingspringboot.common.BaseContext;
import com.zhku.shoppingspringboot.common.CustomException;
import com.zhku.shoppingspringboot.common.R;
import com.zhku.shoppingspringboot.mapper.*;
import com.zhku.shoppingspringboot.pojo.dto.MergeCartDTO;
import com.zhku.shoppingspringboot.pojo.dto.SubmitOrderDTO;
import com.zhku.shoppingspringboot.pojo.entity.*;
import com.zhku.shoppingspringboot.pojo.entity.goodsData.Properties;
import com.zhku.shoppingspringboot.pojo.vo.order.*;
import com.zhku.shoppingspringboot.pojo.vo.SubmitOrderVO;
import com.zhku.shoppingspringboot.service.IOrderSkusService;
import com.zhku.shoppingspringboot.service.IOrdersService;
import io.swagger.models.auth.In;
import org.omg.PortableServer.THREAD_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.zhku.shoppingspringboot.common.ResultCode.ERROR;

/**
 * @author hwy
 * @date 2025-01-02 11:08
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private ShopCartMapper shopCartMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private SkusMapper skusMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private OrderSkusMapper orderSkusMapper;
    @Autowired
    private DetailsMapper detailsMapper;
    @Autowired
    private IOrderSkusService iOrderSkusService;
    @Override
    public CreateOrdersVO createOrder() {
        //查询当前用户的购物车信息
        LambdaQueryWrapper<ShopCart> shopCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopCartLambdaQueryWrapper.eq(ShopCart::getUserId, BaseContext.getCurrentId())
                .eq(ShopCart::getSelected,true)
                .eq(ShopCart::getIsEffective,true);
        List<ShopCart> shopCarts = shopCartMapper.selectList(shopCartLambdaQueryWrapper);
        //筛选出选中且有效的商品
        if(CollUtil.isEmpty(shopCarts)){
            return null;
        }
        //查询当前用户地址列表
        LambdaQueryWrapper<Address> addressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressLambdaQueryWrapper.eq(Address::getUserId,BaseContext.getCurrentId());
        List<Address> addresses = addressMapper.selectList(addressLambdaQueryWrapper);

        //获取商品信息
        List<Long> skuIds = shopCarts.stream().map(shopCart -> shopCart.getSkuId()).collect(Collectors.toList());
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Skus> skusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        skusLambdaQueryWrapper.in(CollUtil.isNotEmpty(skuIds),Skus::getId,skuIds);
        List<Skus> skuses = skusMapper.selectList(skusLambdaQueryWrapper);
        HashMap<Long, Skus> skusHashMap = MapUtil.newHashMap();
        for(Skus skus : skuses){
            skusHashMap.put(skus.getId(),skus);
        }

        List<Long> goodIds = skuses.stream().map(skus -> skus.getGoodsId()).collect(Collectors.toList());
        goodsLambdaQueryWrapper.in(CollUtil.isNotEmpty(goodIds),Goods::getId,goodIds);
        List<Goods> goods = goodsMapper.selectList(goodsLambdaQueryWrapper);
        HashMap<Long, Goods> goodsHashMap = MapUtil.newHashMap();
        for(Goods goods1 : goods){
            goodsHashMap.put(goods1.getId(),goods1);
        }

        //总件数
        Integer goodsCount = 0;
        //总价格
        Float totalPrice = 0F;
        //总实付价格
        Float totalPayPrice = 0F;
        //总邮费
        Float totalPostFee = 0F;

        ArrayList<OrderGoodsMsgVO> orderGoodsMsgVOS = CollUtil.newArrayList();
        //生成订单数据
        for(ShopCart shopCart : shopCarts){
            OrderGoodsMsgVO orderGoodsMsgVO = OrderGoodsMsgVO.builder().count(shopCart.getCount())
                    .payPrice(shopCart.getNowPrice())
                    .totalPayPrice(shopCart.getCount() * shopCart.getNowPrice())
                    .build();
            goodsCount += shopCart.getCount();
            totalPayPrice += shopCart.getCount() * shopCart.getNowPrice();
            totalPostFee += shopCart.getPostFree();
            if(skusHashMap.containsKey(shopCart.getSkuId())){
                Skus skus = skusHashMap.get(shopCart.getSkuId());
                //单价
                orderGoodsMsgVO.setPrice(skus.getPrice());
                //单价小计
                orderGoodsMsgVO.setTotalPrice(skus.getPrice() * shopCart.getCount());
                totalPrice += skus.getPrice() * shopCart.getCount();
                //商品id
                orderGoodsMsgVO.setId(skus.getGoodsId());
                //skuid
                orderGoodsMsgVO.setSkuId(skus.getId());
                if(goodsHashMap.containsKey(skus.getGoodsId())){
                    Goods goods1 = goodsHashMap.get(skus.getGoodsId());
                    orderGoodsMsgVO.setName(goods1.getName());
                    //商品图片
                    orderGoodsMsgVO.setPicture(goods1.getMainPictures());
                }
            }
            orderGoodsMsgVOS.add(orderGoodsMsgVO);
        }
        CreateOrdersVO result = CreateOrdersVO.builder().addresses(addresses)
                .goods(orderGoodsMsgVOS)
                .totalPrice(totalPrice)
                .goodsCount(goodsCount)
                .postFree(totalPostFee)
                .totalPayPrice(totalPayPrice)
                .discount(0F)
                .build();

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SubmitOrderVO submitOrder(SubmitOrderDTO submitOrderDTO) {
        //查询购物车数据
        List<MergeCartDTO> goodsMsg = submitOrderDTO.getGoods();
        List<Long> skuIds = goodsMsg.stream().map(mergeCartDTO -> mergeCartDTO.getSkuId()).collect(Collectors.toList());
        LambdaQueryWrapper<ShopCart> shopCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopCartLambdaQueryWrapper.in(CollUtil.isNotEmpty(skuIds),ShopCart::getSkuId,skuIds)
                .in(ShopCart::getUserId,BaseContext.getCurrentId());
        List<ShopCart> shopCarts = shopCartMapper.selectList(shopCartLambdaQueryWrapper);
        if(CollUtil.isEmpty(shopCarts)){
            throw new CustomException("无数据");
        }
        Float totalPostFree = 0F,totalPayPrice = 0F,totalPrice = 0F;
        Integer totalCount = 0;
        ArrayList<OrderSkus> orderSkus = CollUtil.newArrayList();
        for(ShopCart shopCart : shopCarts){
            totalCount += shopCart.getCount();
            totalPostFree += shopCart.getPostFree();
            totalPayPrice += shopCart.getNowPrice();
            totalPrice += shopCart.getNowOriginalPrice();
            //生成order sku数据
            OrderSkus orderSkus1 = BeanUtil.copyProperties(shopCart, OrderSkus.class);
            orderSkus1.setOldPrice(shopCart.getNowOriginalPrice());
            orderSkus1.setPrice(shopCart.getNowPrice());
            orderSkus1.setTotalPayPrice(shopCart.getNowPrice() * shopCart.getCount());
            orderSkus1.setGoodsId(shopCart.getGoodsId());
            orderSkus.add(orderSkus1);
        }
        //生成订单数据
        SubmitOrderVO submitOrderVO = BeanUtil.copyProperties(submitOrderDTO, SubmitOrderVO.class);
        submitOrderVO.setGoodsCount(totalCount);
        submitOrderVO.setTotalPayPrice(totalPayPrice);
        submitOrderVO.setPostFree(totalPostFree);
        submitOrderVO.setTotalPrice(totalPrice);
        submitOrderVO.setOrderState(1);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = df.format(System.currentTimeMillis());
        Timestamp timestamp = Timestamp.valueOf(format);
        submitOrderVO.setCreateTime(format);

        // 创建 Calendar 对象并设置时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(timestamp);

        // 在 Calendar 上加15分钟
        calendar.add(Calendar.MINUTE, 15);

        // 将 Calendar 对象转换回 Timestamp
        Timestamp newTimestamp = new Timestamp(calendar.getTimeInMillis());
        //设置支付时间为15分钟
        submitOrderVO.setPayLatestTime(df.format(newTimestamp));
        Long secondsDifference = (newTimestamp.getTime() - timestamp.getTime()) / 1000;
        submitOrderVO.setCountDown(secondsDifference);
        //设置sku id集合
        submitOrderVO.setSkus(skuIds);


        Orders orders = BeanUtil.copyProperties(submitOrderVO, Orders.class);
        orders.setAddressId(submitOrderDTO.getAddressId());
        orders.setBuyerMessage(submitOrderDTO.getBuyerMessage());
        orders.setDeliveryTimeType(submitOrderVO.getOrderState());
        //设置支付时间
        orders.setPayTime(timestamp);
        //待发货
        orders.setOrderState(2);
        //设置用户id
        orders.setUserId(BaseContext.getCurrentId());
        //插入数据库
        if(save(orders)){
            submitOrderVO.setId(orders.getId());
            //删除购物车数据
            LambdaUpdateWrapper<ShopCart> shopCartLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            shopCartLambdaUpdateWrapper.in(ShopCart::getSkuId,skuIds).eq(ShopCart::getUserId,BaseContext.getCurrentId());

            List<OrderSkus> orderSkuses = orderSkus.stream().map(orderSkus1 -> {
                return orderSkus1.setOrderId(orders.getId());
            }).collect(Collectors.toList());

            if(!iOrderSkusService.saveBatch(orderSkuses)){
                throw new CustomException("插入数据失败");
            }
            if(shopCartMapper.delete(shopCartLambdaUpdateWrapper) == 0){
                throw new CustomException("删除数据库数据失败");
            }
        }else{
            throw new CustomException("插入数据失败");
        }
        return submitOrderVO;
    }

    @Override
    public List<OrderDetailVO> getOrder() {
       // Orders orders = lambdaQuery().eq(Orders::getId, id).one();


        List<Orders> orders = lambdaQuery().eq(Orders::getUserId, BaseContext.getCurrentId()).list();
        if(CollUtil.isEmpty(orders)){
            return CollUtil.newArrayList();
        }
        //获取所有地址
        List<Long> addressIds = orders.stream().map(Orders::getAddressId).collect(Collectors.toList());
        LambdaUpdateWrapper<Address> addressLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        addressLambdaUpdateWrapper.in(Address::getId,addressIds);
        List<Address> address = addressMapper.selectList(addressLambdaUpdateWrapper);
        HashMap<Long, Address> addressHashMap = MapUtil.newHashMap();
        for(Address address1 : address){
            addressHashMap.put(address1.getId(),address1);
        }
        List<Long> ordersIds = orders.stream().map(Orders::getId).collect(Collectors.toList());
        //查找商品规格
        LambdaQueryWrapper<OrderSkus> orderSkusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderSkusLambdaQueryWrapper.in(OrderSkus::getId,ordersIds);
        List<OrderSkus> orderSkuses = orderSkusMapper.selectList(orderSkusLambdaQueryWrapper);
        HashMap<Long, List<OrderSkus>> skudHashMap = MapUtil.newHashMap();
        for(OrderSkus orderSkus : orderSkuses){
            if(skudHashMap.containsKey(orderSkus.getOrderId())){
                List<OrderSkus> orderSkuses1 = skudHashMap.get(orderSkus.getOrderId());
                orderSkuses1.add(orderSkus);
                skudHashMap.put(orderSkus.getOrderId(),orderSkuses1);
            }else{
                skudHashMap.put(orderSkus.getOrderId(),CollUtil.newArrayList(orderSkus));
            }
        }

        List<Long> goodsIds = orderSkuses.stream().map(OrderSkus::getGoodsId).collect(Collectors.toList());
        //获取商品属性
        LambdaQueryWrapper<Details> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.in(CollUtil.isNotEmpty(goodsIds),Details::getGoodsId,goodsIds);
        List<Details> details = detailsMapper.selectList(detailsLambdaQueryWrapper);
        HashMap<Long, List<Details>> detailHashmap = MapUtil.newHashMap();
        for(Details details1 : details){
            List<Details> details2 = detailHashmap.get(details1.getGoodsId());
            if(details2 != null) {
                details2.add(details1);
            }else {
                details2 = CollUtil.newArrayList(details1);
            }
            detailHashmap.put(details1.getGoodsId(),details2);
        }

        ArrayList<OrderDetailVO> result = CollUtil.newArrayList();
        List<Properties> properties = CollUtil.newArrayList();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i = 0 ; i < orders.size() ; i++){
            Orders orders1 = orders.get(i);
            //更新状态
            if(orders1.getOrderState() == 1 && orders1.getCountDown() > -1){
                //未支付 判断是否超时
                String format = df.format(System.currentTimeMillis());

                Timestamp timestamp = Timestamp.valueOf(format);

                Timestamp payLatesTime = orders1.getPayLatestTime();
                if(payLatesTime.compareTo(timestamp) < 0){
                    //已超时
                    orders1.setCountDown(-1L);
                    orders1.setOrderState(6);
                    orders1.setCloseTime(payLatesTime);
                }else{
                    //未超时，更新倒计时
                    long time = payLatesTime.getTime();
                    long time1 = timestamp.getTime();
                    orders1.setCountDown((time - time1) / 1000);
                }
            }

            OrderDetailVO orderDetailVO = BeanUtil.copyProperties(orders1, OrderDetailVO.class,"skus","createTime","payLatestTime","evaluationTime","closeTime","endTime","consignTime","payTime");

            //时间
            orderDetailVO.setCreateTime(df.format(orders1.getCreateTime()));
            orderDetailVO.setPayLatestTime(df.format(orders1.getPayLatestTime()));
            if(orders1.getPayTime() != null){
                orderDetailVO.setPayTime(df.format(orders1.getPayTime()));
            }
            if(orders1.getEndTime() != null){
                orderDetailVO.setEndTime(df.format(orders1.getEndTime()));
            }
            if(orders1.getCloseTime() != null){
                orderDetailVO.setCloseTime(df.format(orders1.getCloseTime()));
            }
            if(orders1.getEvaluationTime() != null){
                orderDetailVO.setEvaluationTime(df.format(orders1.getEvaluationTime()));
            }

            if(addressHashMap.containsKey(orders1.getAddressId())){
                BeanUtil.copyProperties(addressHashMap.get(orders1.getAddressId()),orderDetailVO,"id");
            }
            if(skudHashMap.containsKey(orders1.getId())){
                List<OrderSkus> orderSkuses1 = skudHashMap.get(orders1.getId());
                //设置商品属性
                List<SkuVO> skuVOS = orderSkuses1.stream().map(orderSkus -> {
                    SkuVO skuVO = BeanUtil.copyProperties(orderSkus, SkuVO.class);
                    List<Details> details1 = detailHashmap.get(orderSkus.getOrderId());
                    List<Properties> collect = details1.stream().map(details2 -> BeanUtil.copyProperties(details2, Properties.class, "id", "goodsId")).collect(Collectors.toList());
                    skuVO.setProperties(collect);
                    return skuVO;
                }).collect(Collectors.toList());
                orderDetailVO.setSkus(skuVOS);
            }
            result.add(orderDetailVO);
        }
        return result;
       /* if(ObjectUtil.isEmpty(orders)){
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if(orders.getOrderState() == 1 ){
            //未支付 判断是否超时
            String format = df.format(System.currentTimeMillis());
            Timestamp timestamp = Timestamp.valueOf(format.substring(0, format.length() - 3));

            Timestamp payLatesTime = orders.getPayLatestTime();
            if(payLatesTime.compareTo(timestamp) < 0){
                //已超时
                orders.setCountDown(-1L);
                orders.setOrderState(6);
                orders.setCloseTime(payLatesTime);
            }else{
                //未超时，更新倒计时
                long time = payLatesTime.getTime();
                long time1 = timestamp.getTime();
                orders.setCountDown((time - time1) / 1000);
            }
        }

        OrderDetailVO orderDetailVO = BeanUtil.copyProperties(orders, OrderDetailVO.class,"createTime","payLatestTime","skus","evaluationTime","closeTime","endTime","consignTime","payTime");
        LambdaUpdateWrapper<Address> addressLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        addressLambdaUpdateWrapper.eq(Address::getId,orders.getAddressId());
        Address address = addressMapper.selectOne(addressLambdaUpdateWrapper);
        BeanUtil.copyProperties(address,orderDetailVO);

        //时间
        orderDetailVO.setCreateTime(df.format(orders.getCreateTime()));
        orderDetailVO.setPayLatestTime(df.format(orders.getPayLatestTime()));
        if(orders.getPayTime() != null){
            orderDetailVO.setPayTime(df.format(orders.getPayTime()));
        }
        if(orders.getEndTime() != null){
            orderDetailVO.setEndTime(df.format(orders.getEndTime()));
        }
        if(orders.getCloseTime() != null){
            orderDetailVO.setCloseTime(df.format(orders.getCloseTime()));
        }
        if(orders.getEvaluationTime() != null){
            orderDetailVO.setEvaluationTime(df.format(orders.getEvaluationTime()));
        }

        LambdaQueryWrapper<OrderSkus> orderSkusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderSkusLambdaQueryWrapper.eq(OrderSkus::getId,id);
        List<OrderSkus> orderSkuses = orderSkusMapper.selectList(orderSkusLambdaQueryWrapper);
        //获取商品属性
        List<Long> goodsIds = orderSkuses.stream().map(OrderSkus::getGoodsId).collect(Collectors.toList());
        LambdaQueryWrapper<Details> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.in(CollUtil.isNotEmpty(goodsIds),Details::getGoodsId,goodsIds);
        List<Details> details = detailsMapper.selectList(detailsLambdaQueryWrapper);

        List<SkuVO> skuVOS = orderSkuses.stream().map(orderSkus -> BeanUtil.copyProperties(orderSkus, SkuVO.class)).collect(Collectors.toList());
        List<Properties> properties = CollUtil.newArrayList();
        Properties properties1 = new Properties();
        for(SkuVO skuVO : skuVOS){
            for(Details details1 : details){
                if(details1.getGoodsId() == skuVO.getGoodsId()){
                    properties1.setName(details1.getName());
                    properties1.setValue(details1.getValue());
                    properties.add(properties1);
                }
            }
            skuVO.setProperties(properties);
            CollUtil.clear(properties);
        }
        orderDetailVO.setSkus(skuVOS);
        return orderDetailVO;*/
    }

    @Override
    public R<String> deleteOrder(List<Long> ids) {
       if(! lambdaUpdate().in(Orders::getId,ids).remove()){
           return R.error(ERROR,"删除失败");
       }
       return R.success("删除成功");
    }

    @Override
    public List<OrderDetailVO> getAllOrder() {
        List<Orders> orders = lambdaQuery().list();
        //获取所有地址
        List<Long> addressIds = orders.stream().map(Orders::getAddressId).collect(Collectors.toList());
        LambdaUpdateWrapper<Address> addressLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        addressLambdaUpdateWrapper.in(Address::getId,addressIds);
        List<Address> address = addressMapper.selectList(addressLambdaUpdateWrapper);
        HashMap<Long, Address> addressHashMap = MapUtil.newHashMap();
        for(Address address1 : address){
            addressHashMap.put(address1.getId(),address1);
        }
        List<Long> ordersIds = orders.stream().map(Orders::getId).collect(Collectors.toList());
        //查找商品规格
        LambdaQueryWrapper<OrderSkus> orderSkusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderSkusLambdaQueryWrapper.in(OrderSkus::getId,ordersIds);
        List<OrderSkus> orderSkuses = orderSkusMapper.selectList(orderSkusLambdaQueryWrapper);
        HashMap<Long, List<OrderSkus>> skudHashMap = MapUtil.newHashMap();
        for(OrderSkus orderSkus : orderSkuses){
            if(skudHashMap.containsKey(orderSkus.getOrderId())){
                List<OrderSkus> orderSkuses1 = skudHashMap.get(orderSkus.getOrderId());
                orderSkuses1.add(orderSkus);
                skudHashMap.put(orderSkus.getOrderId(),orderSkuses1);
            }else{
                skudHashMap.put(orderSkus.getOrderId(),CollUtil.newArrayList(orderSkus));
            }
        }

        List<Long> goodsIds = orderSkuses.stream().map(OrderSkus::getGoodsId).collect(Collectors.toList());
        //获取商品属性
        LambdaQueryWrapper<Details> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.in(CollUtil.isNotEmpty(goodsIds),Details::getGoodsId,goodsIds);
        List<Details> details = detailsMapper.selectList(detailsLambdaQueryWrapper);
        HashMap<Long, List<Details>> detailHashmap = MapUtil.newHashMap();
        for(Details details1 : details){
            List<Details> details2 = detailHashmap.get(details1.getGoodsId());
            if(details2 != null) {
                details2.add(details1);
            }else {
                details2 = CollUtil.newArrayList(details1);
            }
            detailHashmap.put(details1.getGoodsId(),details2);
        }

        ArrayList<OrderDetailVO> result = CollUtil.newArrayList();
        List<Properties> properties = CollUtil.newArrayList();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i = 0 ; i < orders.size() ; i++){
            Orders orders1 = orders.get(i);
            //更新状态
            if(orders1.getOrderState() == 1 && orders1.getCountDown() > -1){
                //未支付 判断是否超时
                String format = df.format(System.currentTimeMillis());

                Timestamp timestamp = Timestamp.valueOf(format);

                Timestamp payLatesTime = orders1.getPayLatestTime();
                if(payLatesTime.compareTo(timestamp) < 0){
                    //已超时
                    orders1.setCountDown(-1L);
                    orders1.setOrderState(6);
                    orders1.setCloseTime(payLatesTime);
                }else{
                    //未超时，更新倒计时
                    long time = payLatesTime.getTime();
                    long time1 = timestamp.getTime();
                    orders1.setCountDown((time - time1) / 1000);
                }
            }

            OrderDetailVO orderDetailVO = BeanUtil.copyProperties(orders1, OrderDetailVO.class,"skus","createTime","payLatestTime","evaluationTime","closeTime","endTime","consignTime","payTime");

            //时间
            orderDetailVO.setCreateTime(df.format(orders1.getCreateTime()));
            orderDetailVO.setPayLatestTime(df.format(orders1.getPayLatestTime()));
            if(orders1.getPayTime() != null){
                orderDetailVO.setPayTime(df.format(orders1.getPayTime()));
            }
            if(orders1.getEndTime() != null){
                orderDetailVO.setEndTime(df.format(orders1.getEndTime()));
            }
            if(orders1.getCloseTime() != null){
                orderDetailVO.setCloseTime(df.format(orders1.getCloseTime()));
            }
            if(orders1.getEvaluationTime() != null){
                orderDetailVO.setEvaluationTime(df.format(orders1.getEvaluationTime()));
            }

            if(addressHashMap.containsKey(orders1.getAddressId())){
                BeanUtil.copyProperties(addressHashMap.get(orders1.getAddressId()),orderDetailVO,"id");
            }
            if(skudHashMap.containsKey(orders1.getId())){
                List<OrderSkus> orderSkuses1 = skudHashMap.get(orders1.getId());
                //设置商品属性
                List<SkuVO> skuVOS = orderSkuses1.stream().map(orderSkus -> {
                    SkuVO skuVO = BeanUtil.copyProperties(orderSkus, SkuVO.class);
                    List<Details> details1 = detailHashmap.get(orderSkus.getOrderId());
                    List<Properties> collect = details1.stream().map(details2 -> BeanUtil.copyProperties(details2, Properties.class, "id", "goodsId")).collect(Collectors.toList());
                    skuVO.setProperties(collect);
                    return skuVO;
                }).collect(Collectors.toList());
                orderDetailVO.setSkus(skuVOS);
            }
            result.add(orderDetailVO);
            }

            return result;
        }

    @Override
    public R<String> sendOrder(Long id) {
        Orders orders = this.lambdaQuery().eq(Orders::getId,id).one();
        if(ObjectUtil.isEmpty(orders)){
            return R.error(ERROR,"数据不存在");
        }
        if(orders.getOrderState() == 2 ){
            orders.setOrderState(3);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = df.format(System.currentTimeMillis());
            Timestamp timestamp = Timestamp.valueOf(format);
            orders.setConsignTime(timestamp);

            //设置预计到货时间
            // 创建 Calendar 对象并设置时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(timestamp);

            // 在 Calendar 上加3天
            calendar.add(Calendar.HOUR, 3*24);

            // 将 Calendar 对象转换回 Timestamp
            Timestamp newTimestamp = new Timestamp(calendar.getTimeInMillis());
            //预计到货时间
            orders.setArrivalEstimatedTime(newTimestamp);
            orders.setOrderState(3);
        }else {
            return R.error(ERROR,"订单状态错误");
        }
        if(!this.lambdaUpdate().eq(Orders::getId,id)
                .update(orders)
        ) {
            return R.error(ERROR, "操作失败");
        }
        return R.success("发货成功");
    }

    @Override
    public R<String> Comment(Long id, String comment) {
        Orders orders = this.lambdaQuery().eq(Orders::getId, id).one();
        if(ObjectUtil.isEmpty(orders)){
            throw new CustomException("无数据");
        }
        if(orders.getOrderState() == 4) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = df.format(System.currentTimeMillis());
            Timestamp timestamp = Timestamp.valueOf(format);
            orders.setComment(comment);
            //设置评论时间
            orders.setEvaluationTime(timestamp);
        }else {
            return R.error(ERROR,"订单状态错误");
        }
        if(!this.lambdaUpdate().eq(Orders::getId,id).update(orders)
        ){
            return R.error(ERROR,"操作失败");
        }
        return R.success("评论成功");
    }

    @Override
    public R<String> correctOrder(Long id) {
        Orders orders = this.lambdaQuery().eq(Orders::getId, id).one();
        if(ObjectUtil.isEmpty(orders)){
            throw new CustomException("无数据");
        }
        if(orders.getOrderState() == 3){
            //确认收货
            orders.setOrderState(4);
        }else {
            return R.error(ERROR,"订单状态错误");
        }
        if(!this.lambdaUpdate().eq(Orders::getId,id).update(orders)
        ){
            return R.error(ERROR,"操作失败");
        }
        return R.success("确认收货成功");
    }

    @Override
    public OrdersStaticVO OrderStatic() {
        List<StaticOrder> staticOrders = baseMapper.StaticCount();
        Integer total1 = 0, total2 = 0,total3 = 0,total4 = 0,total5 = 0;

        for (int i = 0 ; i < staticOrders.size() ; i++) {
            StaticOrder staticOrder = staticOrders.get(i);
            Integer key = staticOrder.getOrderState();
            Integer value = staticOrder.getCount();
            if(key == 1){
                total1 = value;
            }
            if(key == 2){
                total2 = value;
            }
            if(key == 3){
                total3 = value;
            }
            if(key == 4){
                total4 = value;
            }
            if(key == 5){
                total5 = value;
            }
        }
        return OrdersStaticVO.builder().noPayTotal(total1)
                .noSendTotal(total2)
                .sendTotal(total3)
                .finishTotal(total4)
                .cancelTotal(total5)
                .build();
    }
}
